<?php
    /**
     * User zgh
     * Email 1803897171@qq.com
     * Date 2021/7/25
     **/

    namespace app\admin\controller;

    use app\admin\service\UploadService;
    use app\common\Annotation\ControllerAnnotation;
    use app\common\Annotation\NodeAnotation;
    use app\common\controller\BackendController;
    use think\facade\Request;


    /**
     * @ControllerAnnotation(title="文件上传",auth=2)
     * Class UploadController
     * @package app\admin\controller
     */
    class UploadController extends BackendController
    {

        /**
         * @NodeAnotation(title="上传管理",auth=2)
         */
        public function index()
        {
            if (Request::isAjax()) {
                $result = UploadService::getList(Request::param());
                return success_json_response("成功", $result['dataList'], ['count' => $result['total']]);
            } else {
                return $this->fetch();
            }
        }

        /**
         * @NodeAnotation(title="添加",auth=2)
         * @return mixed|\think\response\Json
         */
        public function add()
        {
            $params = Request::param();
            if (Request::isAjax()) {
                $form_name = "file";
                $res = UploadService::upload($form_name, $params);
                if ($res) {
                    return success_json_response("上传成功", ["id" => $res]);
                } else {
                    return json_response("上传失败");
                }
            }
            return $this->fetch();
        }

        /**
         * @NodeAnotation(title="删除",auth=2)
         * @return \think\response\Json
         * @throws \app\common\exception\ServiceException
         */
        public function del()
        {
            if (Request::isAjax()) {
                $res = UploadService::del(Request::param());
                return $res ? success_json_response("删除成功") : json_response("删除失败");
            }
        }


        /**
         * 文件上传
         * @NodeAnotation(title="文件上传",auth=1)
         * @return \think\response\Json
         * @throws \app\common\exception\ServiceException
         */
        public function upload()
        {
            $params = Request::param();
            $form_name = "file";
            $is_editor_uploader = false;
            if (isset($params['is_editor']) && $params['is_editor'] == 1) {
                $is_editor_uploader = true;
                $form_name = 'edit';
            }
            $res = UploadService::upload($form_name, $params);
            if ($is_editor_uploader) {
                return success_json_response("成功", $res['src']);
            } else {
                return success_json_response($res);
            }
        }


    }